package com.coder.rental.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coder.rental.entity.Role;
import com.coder.rental.entity.RolePermission;
import com.coder.rental.entity.User;
import com.coder.rental.mapper.RoleMapper;
import com.coder.rental.mapper.RolePermissionMapper;
import com.coder.rental.mapper.UserMapper;
import com.coder.rental.service.IRoleService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tuboyuan
 * @since 2025-09-04
 */
/**
 * 角色服务实现类
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    /**
     * 检查指定角色ID是否关联了用户
     * @param id 角色ID
     * @return 如果有关联用户返回true，否则返回false
     */
    @Override
    public boolean hasUser(Integer id) {
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("role_id",id);
        return userMapper.selectCount(queryWrapper)>0;
    }

    /**
     * 批量删除角色
     * @param ids 以逗号分隔的角色ID字符串
     * @return 删除成功返回true
     */
    @Override
    public boolean delete(String ids) {
        // 将逗号分隔的ID字符串转换为整数列表
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).toList();
        if(!list.isEmpty()){
            for (Integer id : list) {
                // 检查角色是否关联用户，未关联才执行删除操作
                if(!hasUser(id)){
                    // 删除角色权限关联记录
                    rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id",id));
                    // 删除角色记录
                    baseMapper.deleteById(id);
                }
            }
        }
        return true;
    }

    @Override
    public boolean assignPermission(Integer roleId, List<Integer> permissionIds) {
        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id",roleId);
        rolePermissionMapper.delete(queryWrapper);
        try {
            if (permissionIds != null && !permissionIds.isEmpty()) {
                for (Integer permissionId : permissionIds) {
                    RolePermission rolePermission = new RolePermission();
                    rolePermission.setRoleId(roleId);
                    rolePermission.setPermissionId(permissionId);
                    rolePermissionMapper.insert(rolePermission);
                }
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }


    @Resource
    private UserMapper userMapper;

    /**
     * 分页查询角色列表
     * @param page 分页参数
     * @param role 查询条件角色对象
     * @return 分页结果
     */
    @Override
    public Page<Role> selectList(Page<Role> page, Role role) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        // 根据角色名称模糊查询
        // 如果角色名不为空，则添加角色名的模糊查询条件
        queryWrapper.like(StrUtil.isNotEmpty(role.getRoleName()),"role_name",role.getRoleName());
        // 按创建时间升序排序
        queryWrapper.orderByAsc("create_time");
        // 获取创建者的ID
        Integer userId = role.getCreaterId();
        //获取创建者信息
        User user = userMapper.selectById(role.getId());
        // 非管理员用户只能查询自己创建的角色
        if(user !=null&&user.getIsAdmin()!=1) {
            queryWrapper.eq("creater_id",userId);
        }
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<Integer> selectRoleIdByUserId(Integer userId) {
        return baseMapper.selectRoleIdByUserId(userId);
    }
}

